查看原文
其他

使用Feign实现Form表单提交

周立 IT牧场 2021-08-10

之前,笔者写了《使用Spring Cloud Feign上传文件》。近日,有同事在对接遗留的Struts古董系统,需要使用Feign实现Form表单提交。其实步骤大同小异,本文附上步骤,算是对之前那篇的补充。

1 添加依赖:

  1. <dependency>

  2.  <groupId>io.github.openfeign.form</groupId>

  3.  <artifactId>feign-form</artifactId>

  4.  <version>3.2.2</version>

  5. </dependency>

  6. <dependency>

  7.  <groupId>io.github.openfeign.form</groupId>

  8.  <artifactId>feign-form-spring</artifactId>

  9.  <version>3.2.2</version>

  10. </dependency>

2 Feign Client示例:

  1. @FeignClient(name = "xxx", url = "http://www.itmuch.com/", configuration = TestFeignClient.FormSupportConfig.class)

  2. public interface TestFeignClient {

  3.    @PostMapping(value = "/test",

  4.            consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE},

  5.            produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}

  6.            )

  7.    void post(Map<String, ?> queryParam);

  8.    class FormSupportConfig {

  9.        @Autowired

  10.        private ObjectFactory<HttpMessageConverters> messageConverters;

  11.        // new一个form编码器,实现支持form表单提交

  12.        @Bean

  13.        public Encoder feignFormEncoder() {

  14.            return new SpringFormEncoder(new SpringEncoder(messageConverters));

  15.        }

  16.        // 开启Feign的日志

  17.        @Bean

  18.        public Logger.Level logger() {

  19.            return Logger.Level.FULL;

  20.        }

  21.    }

  22. }

3 调用示例:

  1. @GetMapping("/user/{id}")

  2. public User findById(@PathVariable Long id) {

  3.  HashMap<String, String> param = Maps.newHashMap();

  4.  param.put("username","zhangsan");

  5.  param.put("password","pwd");

  6.  this.testFeignClient.post(param);

  7.  return new User();

  8. }

4日志:

  1. ...[TestFeignClient#post] ---> POST http://www.baidu.com/test HTTP/1.1

  2. ...[TestFeignClient#post] Accept: application/json;charset=UTF-8

  3. ...[TestFeignClient#post] Content-Type: application/x-www-form-urlencoded; charset=UTF-8

  4. ...[TestFeignClient#post] Content-Length: 30

  5. ...[TestFeignClient#post]

  6. ...[TestFeignClient#post] password=pwd&username=zhangsan

  7. ...[TestFeignClient#post] ---> END HTTP (30-byte body)

由日志可知,此时Feign已能使用Form表单方式提交数据。

参考文档

  • https://github.com/OpenFeign/feign-form

  • https://stackoverflow.com/questions/35803093/how-to-post-form-url-encoded-data-with-spring-cloud-feign



========


    您可能也对以下帖子感兴趣

    文章有问题?点此查看未经处理的缓存